//检查当前版本
var wgtVer = null;

function plusReady() {
	// ......
	// 获取本地应用资源版本号
	plus.runtime.getProperty(plus.runtime.appid, function(inf) {
		wgtVer = inf.version;
		console.log("当前应用版本：" + wgtVer);
		document.getElementById('version').innerHTML = '<p>当前版本：' + wgtVer + '</p>';
	});
}
if (window.plus) {
	plusReady();
} else {
	document.addEventListener('plusready', plusReady, false);
}
// 检测更新：版本检查地址
// 测试地址，返回版本号2.0
var checkUrl = "http://demo.dcloud.net.cn/test/update/check.php";

function checkUpdate() {
	plus.nativeUI.showWaiting("检测更新...");
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch (xhr.readyState) {
			case 4:
				plus.nativeUI.closeWaiting();
				if (xhr.status == 200) {
					console.log("检测更新成功：" + xhr.responseText);
					var newVer = xhr.responseText;
					if (wgtVer && newVer && (wgtVer != newVer)) {
						downWgt(); // 下载升级包
					} else {
						plus.nativeUI.alert("无新版本可更新！");
					}
				} else {
					console.log("检测更新失败！");
					plus.nativeUI.alert("检测更新失败！");
				}
				break;
			default:
				break;
		}
	}
	xhr.open('GET', checkUrl);
	xhr.send();
}
// 下载wgt文件：服务器上获取升级包资源
var wgtUrl = "http://7xkpsb.com1.z0.glb.clouddn.com/H54DB1D89.zip";

function downWgt() {
	plus.nativeUI.showWaiting("下载wgt文件...");
	plus.downloader.createDownload(wgtUrl, {
		filename: "_doc/update/"
	}, function(d, status) {
		if (status == 200) {
			console.log("下载wgt成功：" + d.filename);
			plus.nativeUI.al
			installWgt(d.filename); // 安装wgt包
		} else {
			console.log("下载wgt失败！");
			plus.nativeUI.alert("下载wgt失败！");
		}
		plus.nativeUI.closeWaiting();
	}).start();
}
// 更新应用资源：安装升级包资源
function installWgt(path) {
	plus.nativeUI.showWaiting("安装wgt文件...");
	plus.runtime.install(path, {}, function() {
		plus.nativeUI.closeWaiting();
		console.log("安装wgt文件成功！");
		plus.nativeUI.alert("应用资源更新完成！", function() {
			plus.runtime.restart();
		});
	}, function(e) {
		plus.nativeUI.closeWaiting();
		console.log("安装wgt文件失败[" + e.code + "]：" + e.message);
		plus.nativeUI.alert("安装wgt文件失败[" + e.code + "]：" + e.message);
	});
}

//请求资源包差量更新
function checkUpdate2() {
	var url = 'http://demo.dcloud.net.cn/helloh5/update/HelloH5.wgtu';
	plus.nativeUI.showWaiting("升级中...");
	var dtask = plus.downloader.createDownload(url, {
		method: "GET"
	}, function(d, status) {
		if (status == 200) {
			console.log("Download wgtu success: " + d.filename);
			plus.runtime.install(d.filename, {}, function() {
				plus.nativeUI.closeWaiting();
				plus.nativeUI.alert("Update wgtu success, restart now!", function() {
					plus.runtime.restart();
				});
			}, function(e) {
				plus.nativeUI.closeWaiting();
				alert("Update wgtu failed: " + e.message);
			});
		} else {
			plus.nativeUI.closeWaiting();
			alert("Download wgtu failed: " + status);
		}
	});
	dtask.addEventListener('statechanged', function(d, status) {
		console.log("statechanged: " + d.state);
	});
	dtask.start();
}